<?php
/**
 * User: wangzd
 * Email: wangzhoudong@liwejia.com
 * Date: 2016/11/30
 * Time: 19:53
 */
namespace LWJ\Services\Pay;

class LwjPay {


    /**
     * 创建支付
     * @param $data
     */
    public static function chargeCreate($data,$rsa_public_key) {
        return self::post('/pay/charge/create',$data,$rsa_public_key);
    }

    public static function getPayUrl($payId) {
        return env('PAY_URL') . "pay/index/" . $payId;
    }

    public static function chargeFind($payId,$rsa_public_key) {
        return self::post('/pay/find',['payId'=>$payId],$rsa_public_key);
    }

    public static function post($url,$data,$rsa_public_key) {
        $url = env('PAY_URL') . ltrim($url,'/');
        $headers = array(
            'Content-Type:application/json;charset=utf-8',
            'LWJ-SEND-PAY-SIGN:' . self::getSign($data,$rsa_public_key)
        );

        $data = json_encode($data);
        $ch = curl_init(); //初始化curl
        curl_setopt($ch, CURLOPT_URL, $url);//设置链接
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//设置是否返回信息
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);//设置HTTP头
        curl_setopt($ch, CURLOPT_POST, 1);//设置为POST方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//POST数据
        $responseText = curl_exec($ch);//接收返回信息
        $errorMsg = '';
        if(curl_errno($ch)){//出错则显示错误信息
            $errorMsg =  curl_error($ch);
        }
        $responseStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch); //关闭curl链接
        if($responseStatus===200) {
            return json_decode($responseText,true);
        }
        return ['status'=>$responseStatus,'msg'=>$errorMsg];
    }

    public static function getSign($data ,$rsa_public_key) {
        ksort($data);
        reset($data);
        return md5(json_encode($data) . $rsa_public_key);
    }


    /*
     * $rsa_public_key 用于验证的公钥
     */
    public static function getNoticeData($rsa_public_key) {
        $raw_data = file_get_contents('php://input');
        $signature = request()->header('LWJ-PAY-SIGN');
        if(!$signature) {
            return false;
        }
        $ok = openssl_verify($raw_data, base64_decode($signature), $rsa_public_key, 'sha256');
        if($ok==!1) {
            return false;
        }
        $raw_data = json_decode($raw_data,true);
        return $raw_data;
    }
}
